<template>
  <div id="editor" ref="aceDom" :style="{ height: height + 'px' }"></div>
</template>

<script>
import ace from 'ace-builds'
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/webpack-resolver'
import 'ace-builds/src-noconflict/theme-github'
import 'ace-builds/src-noconflict/mode-javascript'
import 'ace-builds/src-noconflict/mode-json'
import 'ace-builds/src-noconflict/mode-text'
import 'ace-builds/src-noconflict/snippets/json'
import 'ace-builds/src-noconflict/snippets/javascript'
import 'ace-builds/src-noconflict/snippets/text'
// eslint-disable-next-line import/no-unresolved
import workerJavascriptUrl from 'file-loader?esModule=false!ace-builds/src-noconflict/worker-javascript'
// eslint-disable-next-line import/no-unresolved
import workerJsonUrl from 'file-loader?esModule=false!ace-builds/src-noconflict/worker-json'

export default {
  props: {
    code: {
      type: String,
      default: ''
    },
    language: {
      type: String,
      default: 'json'
    },
    height: {
      type: Number,
      default: 200
    }
  },
  data() {
    return {
      aceEditor: null,
      langType: `ace/mode/${this.language}`,
      themeType: `ace/theme/github`
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.aceEditor && this.aceEditor.destroy()
    this.aceEditor = null
  },
  methods: {
    init() {
      const aceDom = this.$refs.aceDom
      ace.config.setModuleUrl('ace/mode/json_worker', workerJsonUrl)
      ace.config.setModuleUrl('ace/mode/javascript_worker', workerJavascriptUrl)
      this.aceEditor = ace.edit(aceDom, {
        theme: this.themeType,
        mode: this.langType,
        useWorker: true,
        enableSnippets: true,
        enableBasicAutocompletion: true,
        enableKeyboardAccessibility: true,
        enableLiveAutocompletion: true,
        enableAutoIndent: true,
        showPrintMargin: false,
        highlightActiveLine: true
      })
      this.aceEditor.setValue(this.code)

      if (this.language === 'json') {
        this.format(this.code)
        this.aceEditor.on('paste', this.handleFormat)
      }
    },
    // json格式自动格式化
    handleFormat(value) {
      try {
        JSON.parse(value.text)
      } catch (e) {
        return
      }

      var formatJson = JSON.stringify(JSON.parse(value.text), null, 2)
      setTimeout(() => {
        this.aceEditor.setValue(formatJson)
      }, 100)
    },
    format(code) {
      try {
        JSON.parse(code)
      } catch (e) {
        return
      }

      var formatJson = JSON.stringify(JSON.parse(code), null, 2)
      setTimeout(() => {
        this.aceEditor.setValue(formatJson)
      }, 100)
    }
  }
}
</script>

<style lang="scss" scoped>
#editor {
  width: 100%;
}
</style>
